import 'dart:convert';

import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
import 'package:encrypt/encrypt.dart';

import '../../src/platform/platform_apis.dart';

extension StringExtentions on String {
  String md5String() {
    var content = new Utf8Encoder().convert(this);
    var digest = md5.convert(content);
    return hex.encode(digest.bytes);
  }

  String aesString(String aesKey, String aesIV, {mode: AESMode.cbc}) {
    final key = Key.fromUtf8(String.fromCharCodes(latin1.encode(aesKey)));
    final iv = IV.fromUtf8(String.fromCharCodes(latin1.encode(aesIV)));
    final encrypter = Encrypter(AES(key, mode: mode));
    final encrypted = encrypter.encrypt(this, iv: iv);
    return encrypted.base64;
  }

  bool isMobile() {
    return this.length == 11 && RegExp("[1-9]{1}[0-9]{10}").hasMatch(this) ||
        this.isPhoneNumber();
  }

  bool isPhoneNumber() {
    if (this.length > 16 || this.length < 9) return false;
    return hasMatch(r'^[+]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\s\./0-9]*$');
  }

  bool hasMatch(String pattern) {
    return RegExp(pattern).hasMatch(this);
  }

  bool isEmail() {
    return RegExp(
                "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}\$")
            .stringMatch(this) ==
        this;
  }

  ///判断是否是身份证
  bool isIdentity() {
    return (this.length == 18 && RegExp("[0-9]{18}").hasMatch(this)) ||
        (this.length == 15 && RegExp("[0-9]{15}").hasMatch(this));
  }

  bool isSmsCode({int len = 4}) {
    return this.length == len && RegExp("[0-9]{$len}").hasMatch(this);
  }

  Future<void> launchUrl() => PlatformApis.launchUrl(this);

  Future<bool> makeCall() => PlatformApis.makeCall(this);

  String appendQueryParameterToUrl(Map<String, dynamic> parameters) {
    if (parameters.isEmpty) return this;
    final hasQuestionMark = this.contains("?");
    final sb = StringBuffer();

    parameters.forEach((key, value) {
      if (value != null) sb.write("&$key=$value");
    });
    return this + (hasQuestionMark ? "&" : "?") + "xx=xx" + sb.toString();
  }
}
